<%#
 Copyright 2013-2020 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= packageName %>.web.rest;

<%_

let mapsIdEntity;
let mapsIdEntityInstance;
let mapsIdRepoInstance;
if (isUsingMapsId) {
    mapsIdEntity = mapsIdAssoc.otherEntityNameCapitalized;
    mapsIdEntityInstance =  mapsIdEntity.charAt(0).toLowerCase() + mapsIdEntity.slice(1);
    mapsIdRepoInstance = `${mapsIdEntityInstance}Repository`;
}

let callBlock = '';
let callListBlock = '';
if (reactive) {
    callBlock = ".block()";
    callListBlock = ".collectList().block()";
}
let saveMethod = 'save';
if (!reactive && databaseType === 'sql') {
    saveMethod = 'saveAndFlush';
}
let createEntityPrefix = '';
let createEntityPostfix = '';
if (databaseType === 'sql' && reactive) {
    createEntityPrefix = 'em.insert(';
    createEntityPostfix = ').block()';
}
let idValue = `${asEntity(entityInstance)}.getId()`;
if (primaryKeyType === 'Long') {
    idValue = idValue + '.intValue()';
} else if (primaryKeyType === 'UUID') {
    idValue = idValue + '.toString()';
}
let transactionalAnnotation = '';
if (databaseType === 'sql' && !reactive) {
    transactionalAnnotation = '\n    @Transactional';
}

_%>
<%_ if (databaseType === 'cassandra') { _%>
import <%= packageName %>.AbstractCassandraTest;
<%_ } _%>
<%_ if (databaseType === 'neo4j') { _%>
import <%= packageName %>.AbstractNeo4jIT;
<%_ } _%>
<%_ if (cacheProvider === 'redis') { _%>
import <%= packageName %>.RedisTestContainerExtension;
<%_ } _%>
<%_ if (reactiveSqlTestContainers) { _%>
import <%= packageName %>.ReactiveSqlTestContainerExtension;
<%_ } _%>
import <%= packageName %>.<%= mainClass %>;
<%_ if (authenticationType === 'uaa') { _%>
import <%= packageName %>.config.SecurityBeanOverrideConfiguration;
<%_ } _%>
<%_ if (authenticationType === 'oauth2') { _%>
import <%= packageName %>.config.TestSecurityConfiguration;
<%_ } _%>
import <%= packageName %>.domain.<%= asEntity(entityClass) %>;
<%_
    var imported = [];
    for (idx in relationships) { // import entities in required relationships
        const relationshipValidate = relationships[idx].relationshipValidate;
        const otherEntityNameCapitalized = relationships[idx].otherEntityNameCapitalized;
        const isUsingMapsIdL1 = relationships[idx].useJPADerivedIdentifier;
        if (imported.indexOf(otherEntityNameCapitalized) === -1) {
            if ((relationshipValidate !== null && relationshipValidate === true) || jpaMetamodelFiltering || (isUsingMapsIdL1 === true)) { _%>
import <%= packageName %>.domain.<%= asEntity(otherEntityNameCapitalized) %>;
<%_         imported.push(otherEntityNameCapitalized);
        } } } _%>
<%_ if (saveUserSnapshot) { _%>
import <%= packageName %>.repository.UserRepository;
<%_ } _%>
import <%= packageName %>.repository.<%= entityClass %>Repository;
<%_ if (databaseType === 'sql' && reactive) { _%>
import <%= packageName %>.service.EntityManager;
<%_ } _%>
<%_ if (isUsingMapsId === true && ( dto !== 'mapstruct' && service === 'no')) { _%>
import <%= packageName %>.repository.<%= mapsIdAssoc.otherEntityNameCapitalized %>Repository;
<%_ } _%>
<%_ if (searchEngine === 'elasticsearch') { _%>
import <%= packageName %>.repository.search.<%= entityClass %>SearchRepository;
<%_ } _%>
<%_ if (service !== 'no') { _%>
import <%= packageName %>.service.<%= entityClass %>Service;
<%_ } _%>
<%_ if (dto === 'mapstruct') { _%>
import <%= packageName %>.service.dto.<%= asDto(entityClass) %>;
import <%= packageName %>.service.mapper.<%= entityClass %>Mapper;
<%_ } _%>
<%_ if (jpaMetamodelFiltering) { _%>
import <%= packageName %>.service.dto.<%= entityClass %>Criteria;
import <%= packageName %>.service.<%= entityClass %>QueryService;
<%_ } _%>

<%_ if (databaseType === 'sql' && reactive) { _%>
import org.junit.jupiter.api.AfterEach;
<%_ } _%>
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
<%_ if ((searchEngine === 'elasticsearch' || fieldsContainOwnerManyToMany || cacheProvider === 'redis') || databaseType === 'neo4j' || reactiveSqlTestContainers) { _%>
import org.mockito.Mock;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
<%_ } _%>
import org.springframework.beans.factory.annotation.Autowired;
<%_ if (!reactive) { _%>
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
<%_ } else { _%>
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
<%_ } _%>
import org.springframework.boot.test.context.SpringBootTest;
<%_ if (searchEngine === 'elasticsearch' && pagination !== 'no' || fieldsContainOwnerManyToMany) { _%>
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
<%_ } _%>
import org.springframework.http.MediaType;
<%_ if (databaseType === 'couchbase') { _%>
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.TestSecurityContextHolder;
<%_ } _%>
import org.springframework.security.test.context.support.WithMockUser;
<%_ if (reactiveRepositories) { _%>
import org.springframework.test.web.reactive.server.WebTestClient;
<%_ } _%>
<%_ if (!reactive) { _%>
import org.springframework.test.web.servlet.MockMvc;
<%_ } _%>
<%_ if (databaseType === 'sql' && !reactive) { _%>
import org.springframework.transaction.annotation.Transactional;
<%_ } _%>
<%_ if (fieldsContainBlob === true) { _%>
import org.springframework.util.Base64Utils;
<%_ } _%>
<%_ if (reactive && (fieldsContainOwnerManyToMany === true || searchEngine === 'elasticsearch')) { _%>
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
<%_ } _%>
<%_ if (databaseType === 'sql' && !reactive) { _%>
import javax.persistence.EntityManager;<% } %><% if (fieldsContainBigDecimal === true) { %>
import java.math.BigDecimal;<% } %><% if (fieldsContainBlob === true && databaseType === 'cassandra') { %>
import java.nio.ByteBuffer;<% } %><% if (reactiveRepositories || fieldsContainDuration === true) { %>
import java.time.Duration;<% } %><% if (fieldsContainLocalDate === true) { %>
import java.time.LocalDate;<% } %><% if (fieldsContainInstant === true || fieldsContainZonedDateTime === true) { %>
import java.time.Instant;<% } %><% if (fieldsContainZonedDateTime === true) { %>
import java.time.ZonedDateTime;
import java.time.ZoneOffset;<% } %><% if (fieldsContainLocalDate === true || fieldsContainZonedDateTime === true) { %>
import java.time.ZoneId;<% } %><% if (fieldsContainInstant === true) { %>
import java.time.temporal.ChronoUnit;<% } %>
<%_ if (fieldsContainOwnerManyToMany) { _%>
import java.util.ArrayList;
<%_ } _%>
<%_ if (searchEngine === 'elasticsearch' && !reactive) { _%>
import java.util.Collections;
<%_ } _%>
import java.util.List;
<%_ if (databaseType === 'cassandra' || fieldsContainUUID === true || (databaseType === 'sql' && hasOauthUser === true)) { _%>
import java.util.UUID;
<%_ } _%>

<%_ if (fieldsContainBigDecimal === true) { _%>
import static <%= packageName %>.web.rest.TestUtil.sameNumber;
<%_ } _%>
<%_ if (fieldsContainZonedDateTime === true) { _%>
import static <%= packageName %>.web.rest.TestUtil.sameInstant;
<%_ } _%>
import static org.assertj.core.api.Assertions.assertThat;
<%_ if (searchEngine === 'elasticsearch' && !reactive) { _%>
import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
<%_ } _%>
import static org.hamcrest.Matchers.hasItem;
<%_ if (reactive) { _%>
import static org.hamcrest.Matchers.is;
<%_ } _%>
<%_ if (testsNeedCsrf) { _%>
    <%_ if (reactive) { _%>
import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf;
    <%_ } else { _%>
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
    <%_ } _%>
<%_ } _%>
<%_ if (searchEngine === 'elasticsearch' || fieldsContainOwnerManyToMany === true) { _%>
import static org.mockito.Mockito.*;
<%_ } _%>
<%_ if (!reactive) { _%>
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
<%_ } _%>

<%_ for (idx in fields) { if (fields[idx].fieldIsEnum === true) { _%>import <%= packageName %>.domain.enumeration.<%= fields[idx].fieldType %>;
<%_ } } _%>
/**
 * Integration tests for the {@link <%= entityClass %>Resource} REST controller.
 */
<%_ if (authenticationType === 'oauth2') { _%>
@SpringBootTest(classes = { <%= mainClass %>.class, TestSecurityConfiguration.class })
<%_ } else if (authenticationType === 'uaa' && applicationType !== 'uaa') { _%>
@SpringBootTest(classes = { SecurityBeanOverrideConfiguration.class, <%= mainClass %>.class })
<%_ } else { _%>
@SpringBootTest(classes = <%= mainClass %>.class)
<%_ } _%>
<%_ if (cacheProvider === 'redis') { _%>
@ExtendWith({ RedisTestContainerExtension.class, MockitoExtension.class })
<%_ } else if (searchEngine === 'elasticsearch' || fieldsContainOwnerManyToMany === true) { _%>
@ExtendWith(MockitoExtension.class)
<%_ } _%>
<%_ if (databaseType === 'neo4j') { _%>
@ExtendWith(AbstractNeo4jIT.class)
<%_ } _%>
<%_ if (reactiveSqlTestContainers) { _%>
@ExtendWith(ReactiveSqlTestContainerExtension.class)
<%_ } _%>
<%_ if (!reactive) { _%>
@AutoConfigureMockMvc
<%_ } else { _%>
@AutoConfigureWebTestClient
<%_ } _%>
@WithMockUser
class <%= entityClass %>ResourceIT <% if (databaseType === 'cassandra') { %>extends AbstractCassandraTest <% } %>{
    <%_ for (idx in fields) {
    const defaultValueName = 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase();
    const updatedValueName = 'UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase();
    const smallerValueName = 'SMALLER_' + fields[idx].fieldNameUnderscored.toUpperCase();
    const needsSmallerValueName = jpaMetamodelFiltering && isFilterableType(fields[idx].fieldType)
            && ['BigDecimal', 'Byte', 'Double', 'Duration', 'Float', 'Short', 'Integer', 'Long', 'LocalDate', 'ZonedDateTime'].includes(fields[idx].fieldType);

    let defaultValue = 1;
    let updatedValue = 2;

    if (fields[idx].fieldValidate === true) {
        if (fields[idx].fieldValidateRules.includes('max')) {
            defaultValue = fields[idx].fieldValidateRulesMax;
            updatedValue = parseInt(fields[idx].fieldValidateRulesMax) - 1;
        }
        if (fields[idx].fieldValidateRules.includes('min')) {
            defaultValue = fields[idx].fieldValidateRulesMin;
            updatedValue = parseInt(fields[idx].fieldValidateRulesMin) + 1;
        }
        if (fields[idx].fieldValidateRules.includes('minbytes')) {
            defaultValue = fields[idx].fieldValidateRulesMinbytes;
            updatedValue = fields[idx].fieldValidateRulesMinbytes;
        }
        if (fields[idx].fieldValidateRules.includes('maxbytes')) {
            updatedValue = fields[idx].fieldValidateRulesMaxbytes;
        }
    }

    const fieldType = fields[idx].fieldType;
    const fieldTypeBlobContent = fields[idx].fieldTypeBlobContent;
    const isEnum = fields[idx].fieldIsEnum;
    let enumValue1;
    let enumValue2;
    if (isEnum) {
        const enumValues = fields[idx].enumValues;
        enumValue1 = enumValues[0];
        if (enumValues.length > 1) {
            enumValue2 = enumValues[1];
        } else {
            enumValue2 = enumValue1;
        }
    }

    if (fieldType === 'String' || fieldTypeBlobContent === 'text') {
        // Generate Strings, using the min and max string length if they are configured
        let sampleTextString = "";
        let updatedTextString = "";
        let sampleTextLength = 10;
        if (fields[idx].fieldValidateRulesMinlength > sampleTextLength) {
            sampleTextLength = fields[idx].fieldValidateRulesMinlength;
        }
        if (fields[idx].fieldValidateRulesMaxlength < sampleTextLength) {
            sampleTextLength = fields[idx].fieldValidateRulesMaxlength;
        }
        for (let i = 0; i < sampleTextLength; i++) {
            sampleTextString += "A";
            updatedTextString += "B";
        }
        if (fields[idx].fieldValidateRulesPattern !== undefined) {
            // Generate Strings, using pattern
            try {
                const patternRegExp = new RegExp(fields[idx].fieldValidateRulesPattern);
                const randExp = fields[idx].createRandexp();
                // set infinite repetitions max range
                if (!patternRegExp.test(sampleTextString.replace(/\\"/g, '"').replace(/\\\\/g, '\\'))) {
                    sampleTextString = randExp.gen().replace(/\\/g, '\\\\').replace(/"/g, '\\"');
                }
                if (!patternRegExp.test(updatedTextString.replace(/\\"/g, '"').replace(/\\\\/g, '\\'))) {
                    updatedTextString = randExp.gen().replace(/\\/g, '\\\\').replace(/"/g, '\\"');
                }
            } catch (error) {
                log(this.chalkRed('Error generating test value for entity "' + entityClass +
                    '" field "' + fields[idx].fieldName + '" with pattern "' + fields[idx].fieldValidateRulesPattern +
                    '", generating default values for this field. Detailed error message: "' + error.message + '".'));
            }
            if (sampleTextString === updatedTextString) {
                updatedTextString = updatedTextString + "B";
                log(this.chalkRed('Randomly generated first and second test values for entity "' + entityClass +
                    '" field "' + fields[idx].fieldName + '" with pattern "' + fields[idx].fieldValidateRulesPattern +
                    '" in file "' + entityClass + 'ResourceIT" where equal, added symbol "B" to second value.'));
            }
        } _%>

    private static final String <%= defaultValueName %> = "<%- sampleTextString %>";
    private static final String <%= updatedValueName %> = "<%- updatedTextString %>";
    <%_ } else if (fieldType === 'Integer') { _%>

    private static final Integer <%= defaultValueName %> = <%= defaultValue %>;
    private static final Integer <%= updatedValueName %> = <%= updatedValue %>;
        <%_ if (needsSmallerValueName) { _%>
    private static final Integer <%= smallerValueName %> = <%= defaultValue %> - 1;
        <%_ } _%>
    <%_ } else if (fieldType === 'Long') { _%>

    private static final Long <%= defaultValueName %> = <%= defaultValue %>L;
    private static final Long <%= updatedValueName %> = <%= updatedValue %>L;
        <%_ if (needsSmallerValueName) { _%>
    private static final Long <%= smallerValueName %> = <%= defaultValue %>L - 1L;
        <%_ } _%>
    <%_ } else if (fieldType === 'Float') { _%>

    private static final <%= fieldType %> <%= defaultValueName %> = <%= defaultValue %>F;
    private static final <%= fieldType %> <%= updatedValueName %> = <%= updatedValue %>F;
        <%_ if (needsSmallerValueName) { _%>
    private static final <%= fieldType %> <%= smallerValueName %> = <%= defaultValue %>F - 1F;
        <%_ } _%>
    <%_ } else if (fieldType === 'Double') { _%>

    private static final <%= fieldType %> <%= defaultValueName %> = <%= defaultValue %>D;
    private static final <%= fieldType %> <%= updatedValueName %> = <%= updatedValue %>D;
        <%_ if (needsSmallerValueName) { _%>
    private static final <%= fieldType %> <%= smallerValueName %> = <%= defaultValue %>D - 1D;
        <%_ } _%>
    <%_ } else if (fieldType === 'BigDecimal') { _%>

    private static final BigDecimal <%= defaultValueName %> = new BigDecimal(<%= defaultValue %>);
    private static final BigDecimal <%= updatedValueName %> = new BigDecimal(<%= updatedValue %>);
        <%_ if (needsSmallerValueName) { _%>
    private static final BigDecimal <%= smallerValueName %> = new BigDecimal(<%= defaultValue %> - 1);
        <%_ } _%>
    <%_ } else if (fieldType === 'UUID') { _%>

    private static final UUID <%= defaultValueName %> = UUID.randomUUID();
    private static final UUID <%= updatedValueName %> = UUID.randomUUID();
    <%_ } else if (fieldType === 'LocalDate') { _%>

    private static final LocalDate <%= defaultValueName %> = LocalDate.ofEpochDay(0L);
    private static final LocalDate <%= updatedValueName %> = LocalDate.now(ZoneId.systemDefault());
        <%_ if (needsSmallerValueName) { _%>
    private static final LocalDate <%= smallerValueName %> = LocalDate.ofEpochDay(-1L);
        <%_ } _%>
    <%_ } else if (fieldType === 'Instant') { _%>

    private static final Instant <%= defaultValueName %> = Instant.ofEpochMilli(0L);
    private static final Instant <%= updatedValueName %> = Instant.now().truncatedTo(ChronoUnit.MILLIS);
        <%_ if (needsSmallerValueName) { _%>
    private static final Instant <%= smallerValueName %> = Instant.ofEpochMilli(-1L);
        <%_ } _%>
    <%_ } else if (fieldType === 'ZonedDateTime') { _%>

    private static final ZonedDateTime <%= defaultValueName %> = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    private static final ZonedDateTime <%= updatedValueName %> = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
        <%_ if (needsSmallerValueName) { _%>
    private static final ZonedDateTime <%= smallerValueName %> = ZonedDateTime.ofInstant(Instant.ofEpochMilli(-1L), ZoneOffset.UTC);
        <%_ } _%>
    <%_ } else if (fieldType === 'Duration') { _%>

    private static final Duration <%= defaultValueName %> = Duration.ofHours(6);
    private static final Duration <%= updatedValueName %> = Duration.ofHours(12);
        <%_ if (needsSmallerValueName) { _%>
    private static final Duration <%= smallerValueName %> = Duration.ofHours(5);
        <%_ } _%>
    <%_ } else if (fieldType === 'Boolean') { _%>

    private static final Boolean <%= defaultValueName %> = false;
    private static final Boolean <%= updatedValueName %> = true;
    <%_ } else if ((fieldType === 'byte[]' || fieldType === 'ByteBuffer') && fieldTypeBlobContent !== 'text') { _%>

    <%_ if (databaseType !== 'cassandra') { _%>
    private static final byte[] <%= defaultValueName %> = TestUtil.createByteArray(1, "0");
    private static final byte[] <%= updatedValueName %> = TestUtil.createByteArray(1, "1");
    <%_ } else { _%>
    private static final ByteBuffer <%= defaultValueName %> = ByteBuffer.wrap(TestUtil.createByteArray(1, "0"));
    private static final ByteBuffer <%= updatedValueName %> = ByteBuffer.wrap(TestUtil.createByteArray(1, "1"));
    <%_ } _%>
    private static final String <%= defaultValueName %>_CONTENT_TYPE = "image/jpg";
    private static final String <%= updatedValueName %>_CONTENT_TYPE = "image/png";
    <%_ } else if (isEnum) { _%>

    private static final <%= fieldType %> <%= defaultValueName %> = <%= fieldType %>.<%= enumValue1.name %>;
    private static final <%= fieldType %> <%= updatedValueName %> = <%= fieldType %>.<%= enumValue2.name %>;
    <%_ } } _%>

    @Autowired
    private <%= entityClass %>Repository <%= entityInstance %>Repository;
    <%_ if (isUsingMapsId === true && ( dto !== 'mapstruct' && service === 'no')) { _%>
    @Autowired
    private <%= mapsIdEntity %>Repository <%= mapsIdRepoInstance %>;
    <%_ } _%>
    <%_ if (saveUserSnapshot) { _%>

    @Autowired
    private UserRepository userRepository;
    <%_ } _%>
    <%_ if (fieldsContainOwnerManyToMany === true) { _%>

    @Mock
    private <%= entityClass %>Repository <%= entityInstance %>RepositoryMock;
    <%_ } _%>
    <%_ if (dto === 'mapstruct') { _%>

    @Autowired
    private <%= entityClass %>Mapper <%= entityInstance %>Mapper;
    <%_ } if (service !== 'no') { _%>
    <%_ if (fieldsContainOwnerManyToMany === true) { _%>

    @Mock
    private <%= entityClass %>Service <%= entityInstance %>ServiceMock;
    <%_ } _%>

    @Autowired
    private <%= entityClass %>Service <%= entityInstance %>Service;
    <%_ } if (searchEngine === 'elasticsearch') { _%>

    /**
     * This repository is mocked in the <%= packageName %>.repository.search test package.
     *
     * @see <%= packageName %>.repository.search.<%= entityClass %>SearchRepositoryMockConfiguration
     */
    @Autowired
    private <%= entityClass %>SearchRepository mock<%= entityClass %>SearchRepository;
    <%_ } _%>
    <%_ if (jpaMetamodelFiltering) { _%>

    @Autowired
    private <%= entityClass %>QueryService <%= entityInstance %>QueryService;
    <%_ } _%>
    <%_ if (databaseType === 'sql') { _%>

    @Autowired
    private EntityManager em;
    <%_ } _%>
    <%_ if (!reactive) { _%>

    @Autowired
    private MockMvc rest<%= entityClass %>MockMvc;
    <%_ } else { _%>

    @Autowired
    private WebTestClient webTestClient;
    <%_ } _%>

    private <%= asEntity(entityClass) %> <%= asEntity(entityInstance) %>;

<%_ ['DEFAULT_', 'UPDATED_'].forEach((fieldStatus) => { _%>
    /**
     * Create an <% if (fieldStatus === 'UPDATED_') { %>updated <% } %>entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static <%= asEntity(entityClass) %> create<% if (fieldStatus === 'UPDATED_') { _%>Updated<%_ } %>Entity(<% if (databaseType === 'sql') { %>EntityManager em<% } %>) {
        <%_ if (fluentMethods) { _%>
        <%= asEntity(entityClass) %> <%= asEntity(entityInstance) %> = new <%= asEntity(entityClass) %>()<% for (idx in fields) { %>
            .<%= fields[idx].fieldName %>(<%= fieldStatus + fields[idx].fieldNameUnderscored.toUpperCase() %>)<% if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { %>
            .<%= fields[idx].fieldName %>ContentType(<%= fieldStatus + fields[idx].fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE)<% } %><% } %>;
        <%_ } else { _%>
        <%= asEntity(entityClass) %> <%= asEntity(entityInstance) %> = new <%= asEntity(entityClass) %>();
            <%_ for (idx in fields) { _%>
        <%= asEntity(entityInstance) %>.set<%= fields[idx].fieldInJavaBeanMethod %>(<%= fieldStatus + fields[idx].fieldNameUnderscored.toUpperCase() %>);
                <%_ if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { _%>
        <%= asEntity(entityInstance) %>.set<%= fields[idx].fieldInJavaBeanMethod %>ContentType(<%= fieldStatus + fields[idx].fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE);
                <%_ } _%>
            <%_ } _%>
        <%_ } _%>
        <%_
        const alreadyGeneratedEntities = [];
        for (idx in relationships) {
            const relationshipValidate = relationships[idx].relationshipValidate;
            const otherEntityName = relationships[idx].otherEntityName;
            const otherEntityNameCapitalized = relationships[idx].otherEntityNameCapitalized;
            const relationshipType = relationships[idx].relationshipType;
            const relationshipNameCapitalizedPlural = relationships[idx].relationshipNameCapitalizedPlural;
            const relationshipNameCapitalized = relationships[idx].relationshipNameCapitalized;
            const mapsIdUse = relationships[idx].useJPADerivedIdentifier;
            if ((relationshipValidate !== null && relationshipValidate === true) || mapsIdUse === true) { _%>
        // Add required entity
            <%_ if (alreadyGeneratedEntities.indexOf(otherEntityName) == -1) { _%>
    <%_ if (otherEntityName === 'user') { // TODO or other entity has no unique fields _%>
        <%= asEntity(otherEntityNameCapitalized) %> <%= otherEntityName %> = <%= createEntityPrefix %><%= otherEntityNameCapitalized %>ResourceIT.createEntity(<% if (databaseType === 'sql') { %>em<% } %>)<%= createEntityPostfix %>;
                <%_ if (databaseType === 'sql' && !reactive) { _%>
        em.persist(<%= otherEntityName %>);
        em.flush();
                <%_ } _%>
                <%_ if (databaseType === 'mongodb') { _%>
        <%= otherEntityName %>.setId("fixed-id-for-tests");
                <%_ } _%>
    <%_ } else { _%>
        <%= asEntity(otherEntityNameCapitalized) %> <%= otherEntityName %>;
        <%_ if (databaseType === 'sql' && !reactive) { _%>
        if (TestUtil.findAll(em, <%= otherEntityNameCapitalized %>.class).isEmpty()) {
            <%= otherEntityName %> = <%= createEntityPrefix %><%= otherEntityNameCapitalized %>ResourceIT.create<% if (fieldStatus === 'UPDATED_') { %>Updated<% } %>Entity(em)<%= createEntityPostfix %>;
            em.persist(<%= otherEntityName %>);
            em.flush();
        } else {
            <%= otherEntityName %> = TestUtil.findAll(em, <%= otherEntityNameCapitalized %>.class).get(0);
        }
        <%_ } else { _%>
        <%= otherEntityName %> = <%= createEntityPrefix %><%= otherEntityNameCapitalized %>ResourceIT.create<% if (fieldStatus === 'UPDATED_') { %>Updated<% } %>Entity(<% if (databaseType === 'sql') { %>em<% } %>)<%= createEntityPostfix %>;
        <%_ } _%>
        <%_ if (databaseType === 'mongodb') { _%>
        <%= otherEntityName %>.setId("fixed-id-for-tests");
        <%_ } _%>
    <%_ } _%>
            <%_ } _%>
            <%_ if (relationshipType === 'many-to-many' || relationshipType === 'one-to-many') { _%>
        <%= asEntity(entityInstance) %>.get<%= relationshipNameCapitalizedPlural %>().add(<%= otherEntityName %>);
            <%_ } else { _%>
        <%= asEntity(entityInstance) %>.set<%= relationshipNameCapitalized %>(<%= otherEntityName %>);
            <%_ } _%>
        <%_ alreadyGeneratedEntities.push(otherEntityName) _%>
        <%_ } } _%>
        return <%= asEntity(entityInstance) %>;
    }
<%_ }); _%>

    <%_ if (databaseType === 'sql' && reactive) {
        const alreadyGeneratedDeletionCalls = [];
        _%>
    public static void deleteEntities(EntityManager em) {
        try {
        <%_ relationships.forEach(function(rel) {
            if (rel.relationshipType === 'many-to-many' && rel.ownerSide) {
                const joinTableName = getJoinTableName(entityTableName, rel.relationshipName, prodDatabaseType); _%>
                em.deleteAll("<%= joinTableName %>").block();
        <%_ }}); _%>
                em.deleteAll(<%= entityClass %>.class).block();
        } catch (Exception e) {
            // It can fail, if other entities are still referring this - it will be removed later.
        }
    <%_ relationships.forEach(function(rel) {
            if ((rel.relationshipValidate === true || rel.useJPADerivedIdentifier === true) && !alreadyGeneratedDeletionCalls.includes(rel.otherEntityName)) { _%>
        <%= rel.otherEntityNameCapitalized %>ResourceIT.deleteEntities(em);
            <%_ alreadyGeneratedDeletionCalls.push(rel.otherEntityName);
            }
        }); _%>
    }

    @AfterEach
    public void cleanup() {
        deleteEntities(em);
    }

    <%_ } _%>
    <%_ if (reactive && testsNeedCsrf) { _%>
    @BeforeEach
    public void setupCsrf() {
        webTestClient = webTestClient.mutateWith(csrf());
    }

    <%_ } _%>
    @BeforeEach
    public void initTest() {
        <%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'cassandra' || databaseType === 'neo4j') { _%>
        <%= entityInstance %>Repository.deleteAll()<%= callBlock %>;
        <%_ } _%>
        <%_ if (databaseType === 'sql' && reactive) {  _%>
        deleteEntities(em);
        <%_ } _%>
        <%= asEntity(entityInstance) %> = createEntity(<% if (databaseType === 'sql') { %>em<% } %>);
    }
<%_ if (!readOnly) { _%>

    @Test<%= transactionalAnnotation %>
    void create<%= entityClass %>() throws Exception {
        int databaseSizeBeforeCreate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
    <%_ if (reactive && searchEngine === 'elasticsearch') { _%>
        // Configure the mock search repository
        when(mock<%= entityClass %>SearchRepository.save(any()))
            .thenAnswer(invocation -> Mono.just(invocation.getArgument(0)));
    <%_ } _%>
        // Create the <%= entityClass %>
        <%_ if (dto === 'mapstruct') { _%>
        <%= asDto(entityClass) %> <%= asDto(entityInstance) %> = <%= entityInstance %>Mapper.toDto(<%= asEntity(entityInstance) %>);
        <%_ } _%>
        <%_ if (!reactive) { _%>
        rest<%= entityClass %>MockMvc.perform(post("/api/<%= entityApiUrl %>")<% if (testsNeedCsrf) { %>.with(csrf())<% }%>
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(<%= (dto === 'mapstruct' ? asDto(entityInstance) : asEntity(entityInstance))%>)))
            .andExpect(status().isCreated());
        <%_ } else { _%>
        webTestClient.post().uri("/api/<%= entityApiUrl %>")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= (dto === 'mapstruct' ? asDto(entityInstance) : asEntity(entityInstance))%>))
            .exchange()
            .expectStatus().isCreated();
        <%_ } _%>

        // Validate the <%= entityClass %> in the database
        <%_ if (databaseType === 'couchbase') { _%>
        SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
        <%_ } _%>
        List<<%= asEntity(entityClass) %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
        assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeCreate + 1);
        <%= asEntity(entityClass) %> test<%= entityClass %> = <%= entityInstance %>List.get(<%= entityInstance %>List.size() - 1);
        <%_ for (idx in fields) { if (fields[idx].fieldType === 'ZonedDateTime') { _%>
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>()).isEqualTo(<%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>);
        <%_ } else if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { _%>
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>()).isEqualTo(<%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>);
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>ContentType()).isEqualTo(<%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE);
        <%_ } else if (fields[idx].fieldType === 'BigDecimal') { _%>
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>()).isEqualByComparingTo(<%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>);
        <%_ } else { _%>
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>()).isEqualTo(<%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>);
        <%_ }} _%>
        <%_ if (isUsingMapsId === true) { _%>

        // Validate the id for MapsId, the ids must be same
        assertThat(test<%= entityClass %>.getId()).isEqualTo(test<%= entityClass %>.get<%= mapsIdEntity %>().getId());
        <%_ } _%>
        <%_ if (searchEngine === 'elasticsearch') { _%>

        // Validate the <%= entityClass %> in Elasticsearch
        verify(mock<%= entityClass %>SearchRepository, times(1)).save(test<%= entityClass %>);
        <%_ } _%>
    }

    @Test<%= transactionalAnnotation %>
    void create<%= entityClass %>WithExistingId() throws Exception {
        int databaseSizeBeforeCreate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();

        // Create the <%= entityClass %> with an existing ID
        <%= asEntity(entityInstance) %>.setId(<% if (databaseType === 'sql' && hasOauthUser === true) { %>UUID.randomUUID().toString()<% } else if (databaseType === 'sql') { %>1L<% } else if (databaseType === 'mongodb' || databaseType === 'neo4j' || databaseType === 'couchbase') { %>"existing_id"<% } else if (databaseType === 'cassandra') { %>UUID.randomUUID()<% } %>);
        <%_ if (dto === 'mapstruct') { _%>
        <%= asDto(entityClass) %> <%= asDto(entityInstance) %> = <%= entityInstance %>Mapper.toDto(<%= asEntity(entityInstance) %>);
        <%_ } _%>

        // An entity with an existing ID cannot be created, so this API call must fail
        <%_ if (!reactive) { _%>
        rest<%= entityClass %>MockMvc.perform(post("/api/<%= entityApiUrl %>")<% if (testsNeedCsrf) { %>.with(csrf())<% }%>
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(<%= (dto === 'mapstruct' ? asDto(entityInstance) : asEntity(entityInstance)) %>)))
            .andExpect(status().isBadRequest());
        <%_ } else { _%>
        webTestClient.post().uri("/api/<%= entityApiUrl %>")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= (dto === 'mapstruct' ? asDto(entityInstance) : asEntity(entityInstance))%>))
            .exchange()
            .expectStatus().isBadRequest();
        <%_ } _%>

        // Validate the <%= entityClass %> in the database
        <%_ if (databaseType === 'couchbase') { _%>
        SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
        <%_ } _%>
        List<<%= asEntity(entityClass) %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
        assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeCreate);
        <%_ if (searchEngine === 'elasticsearch') { _%>

        // Validate the <%= entityClass %> in Elasticsearch
        verify(mock<%= entityClass %>SearchRepository, times(0)).save(<%= asEntity(entityInstance) %>);
        <%_ } _%>
    }

    <%_ if (databaseType === 'sql' && isUsingMapsId === true) { _%>
    @Test<%= transactionalAnnotation %>
    void update<%= entityClass %>MapsIdAssociationWithNewId() throws Exception {
        // Initialize the database
<%_ if (service !== 'no' && dto !== 'mapstruct') { _%>
        <%= entityInstance %>Service.save(<%= asEntity(entityInstance) %>)<%= callBlock %>;
<%_ } else { _%>
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;
<%_ } _%>
        <%_ const alreadyGeneratedEntities = []; _%>
        int databaseSizeBeforeCreate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();

        <%_ for (idx in relationships) {
            const relationshipValidate = relationships[idx].relationshipValidate;
            const otherEntityName = relationships[idx].otherEntityName;
            const otherEntityNameCapitalized = relationships[idx].otherEntityNameCapitalized;
            const mapsIdUse = relationships[idx].useJPADerivedIdentifier;
            if (mapsIdUse === true) { _%>
        // Add a new parent entity
                <%_ if (alreadyGeneratedEntities.indexOf(otherEntityName) == -1) { _%>
        <%= asEntity(otherEntityNameCapitalized) %> <%= otherEntityName %> = <%= otherEntityNameCapitalized %>ResourceIT.create<% if (otherEntityName !== 'user') { _%>Updated<%_ } %>Entity(<% if (databaseType === 'sql') { %>em<% } %>);
                <%_   if (databaseType === 'sql' && !reactive) { _%>
        em.persist(<%= otherEntityName %>);
        em.flush();
                <%_   } _%>
                <%_ } _%>
        <%_ alreadyGeneratedEntities.push(otherEntityName) _%>
        <%_ } break; } _%>

        // Load the <%= entityInstance %>
        <%= asEntity(entityClass) %> updated<%= asEntity(entityClass) %> = <%= entityInstance %>Repository.findById(<%= asEntity(entityInstance) %>.getId())<%= reactive ? '.block()' : '.get()' %>;
        assertThat(updated<%= asEntity(entityClass) %>).isNotNull();<% if (databaseType === 'sql' && !reactive) { %>
        // Disconnect from session so that the updates on updated<%= asEntity(entityClass) %> are not directly saved in db
        em.detach(updated<%= asEntity(entityClass) %>);<% } %>

        // Update the <%= mapsIdEntity %> with new association value
        updated<%= asEntity(entityClass) %>.set<%= mapsIdEntity %>(<%= alreadyGeneratedEntities.pop() %>);
        <%_ if (dto === 'mapstruct') { _%>
        <%= asDto(entityClass) %> updated<%= asDto(entityClass) %> = <%= entityInstance %>Mapper.toDto(updated<%= asEntity(entityClass) %>);
        assertThat(updated<%= asDto(entityClass) %>).isNotNull();
        <%_ } _%>

        // Update the entity
        <%_ if (reactive) { _%>
        webTestClient.put().uri("/api/<%= entityApiUrl %>")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%_ if (dto === 'mapstruct') { _%>updated<%= asDto(entityClass) %> <%_ } else { _%> updated<%= asEntity(entityClass) %> <%_ } _%>))
            .exchange()
            .expectStatus().isOk();
        <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(put("/api/<%= entityApiUrl %>")<% if (testsNeedCsrf) { %>.with(csrf())<% }%>
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(<%_ if (dto === 'mapstruct') { _%>updated<%= asDto(entityClass) %> <%_ } else { _%> updated<%= asEntity(entityClass) %> <%_ } _%>)))
            .andExpect(status().isOk());
        <%_ } _%>

        // Validate the <%= entityClass %> in the database
        <%_ if (databaseType === 'couchbase') { _%>
        SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
        <%_ } _%>
        List<<%= asEntity(entityClass) %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
        assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeCreate);
        <%= asEntity(entityClass) %> test<%= entityClass %> = <%= entityInstance %>List.get(<%= entityInstance %>List.size() - 1);

        // Validate the id for MapsId, the ids must be same
        // Uncomment the following line for assertion. However, please note that there is a known issue and uncommenting will fail the test.
        // Please look at https://github.com/jhipster/generator-jhipster/issues/9100. You can modify this test as necessary.
        // assertThat(test<%= entityClass %>.getId()).isEqualTo(test<%= entityClass %>.get<%= mapsIdEntity %>().getId());
        <%_ if (searchEngine === 'elasticsearch') { _%>

        // Validate the <%= entityClass %> in Elasticsearch
            <%_ if (service !== 'no' && dto !== 'mapstruct') { _%>
        verify(mock<%= entityClass %>SearchRepository, times(2)).save(<%= asEntity(entityInstance) %>);
            <%_ } else { _%>
        verify(mock<%= entityClass %>SearchRepository, times(1)).save(<%= asEntity(entityInstance) %>);
            <%_ } _%>
        <%_ } _%>
    }
<%_ } _%>
<% for (idx in fields) { %><% if (fields[idx].fieldValidate === true) {
    let required = false;
    if (fields[idx].fieldType !== 'byte[]' && fields[idx].fieldValidate === true && fields[idx].fieldValidateRules.includes('required')) {
        required = true;
    }
    if (required) { %>
    @Test<%= transactionalAnnotation %>
    void check<%= fields[idx].fieldInJavaBeanMethod %>IsRequired() throws Exception {
        int databaseSizeBeforeTest = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
        // set the field null
        <%= asEntity(entityInstance) %>.set<%= fields[idx].fieldInJavaBeanMethod %>(null);

        // Create the <%= entityClass %>, which fails.<% if (dto === 'mapstruct') { %>
        <%= asDto(entityClass) %> <%= asDto(entityInstance) %> = <%= entityInstance %>Mapper.toDto(<%= asEntity(entityInstance) %>);<% } %>


        <%_ if (!reactive) { _%>
        rest<%= entityClass %>MockMvc.perform(post("/api/<%= entityApiUrl %>")<% if (testsNeedCsrf) { %>.with(csrf())<% }%>
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(<%= (dto === 'mapstruct' ? asDto(entityInstance) : asEntity(entityInstance)) %>)))
            .andExpect(status().isBadRequest());
        <%_ } else { _%>
        webTestClient.post().uri("/api/<%= entityApiUrl %>")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= (dto === 'mapstruct' ? asDto(entityInstance) : asEntity(entityInstance))%>))
            .exchange()
            .expectStatus().isBadRequest();
        <%_ } _%>

        <%_ if (databaseType === 'couchbase') { _%>
        SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
        <%_ } _%>
        List<<%= asEntity(entityClass) %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
        assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeTest);
    }
<%_ } } } _%>
<%_ } _%>
<%_ if (reactiveRepositories && pagination === 'no') { _%>

    @Test
    void getAll<%= entityClassPlural %>AsStream() {
        // Initialize the database
        <%_ if (databaseType === 'cassandra') { _%>
        <%= asEntity(entityInstance) %>.setId(UUID.randomUUID());
        <%_ } _%>
        <%= entityInstance %>Repository.save(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        List<<%= entityClass %>> <%= entityInstance %>List = webTestClient.get().uri("/api/<%= entityApiUrl %>")
            .accept(MediaType.APPLICATION_STREAM_JSON)
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentTypeCompatibleWith(MediaType.APPLICATION_STREAM_JSON)
            .returnResult(<%= dto !== 'no' ? asDto(entityClass) : asEntity(entityClass) %>.class)
            .getResponseBody()
            <%_ if (dto !== 'no') { _%>
            .map(<%= entityInstance %>Mapper::toEntity)
            <%_ } _%>
            .filter(<%= asEntity(entityInstance) %>::equals)
            .collectList()
            .block(Duration.ofSeconds(5));

        assertThat(<%= entityInstance %>List).isNotNull();
        assertThat(<%= entityInstance %>List).hasSize(1);
        <%= asEntity(entityClass) %> test<%= entityClass %> = <%= entityInstance %>List.get(0);
        <%_ for (idx in fields) { if (fields[idx].fieldType === 'ZonedDateTime') { _%>
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>()).isEqualTo(<%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>);
        <%_ } else if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { _%>
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>()).isEqualTo(<%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>);
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>ContentType()).isEqualTo(<%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE);
        <%_ } else if (fields[idx].fieldType === 'BigDecimal') { _%>
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>()).isEqualByComparingTo(<%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>);
        <%_ } else { _%>
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>()).isEqualTo(<%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>);
        <%_ }} _%>
    }
<%_  } _%>

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%_ if (databaseType === 'cassandra') { _%>
        <%= asEntity(entityInstance) %>.setId(UUID.randomUUID());
        <%_ } _%>
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List
        <%_ if (!reactive) { _%>
        rest<%= entityClass %>MockMvc.perform(get("/api/<%= entityApiUrl %><% if (databaseType !== 'cassandra') { %>?sort=id,desc<% } %>"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
        <%_ } else { _%>
        webTestClient.get().uri("/api/<%= entityApiUrl %>?sort=id,desc")
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .expectBody()
        <%_ } _%>
        <%_ if (['sql', 'mongodb', 'couchbase', 'cassandra'].includes(databaseType)) {
        _%>
            <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].id").value(hasItem(<%= idValue %>))<%= !reactive ? ')' : '' %><%_ } _%><% for (idx in fields) { %>
            <%_ if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { _%>
            <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= fields[idx].fieldName %>ContentType").value(hasItem(<%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE))<%= !reactive ? ')' : '' %>
            <%_ } _%>
            <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= fields[idx].fieldName %>").value(hasItem(<%
                    if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { %>Base64Utils.encodeToString(<% } else
                        if (fields[idx].fieldType === 'ZonedDateTime') { %>sameInstant(<% } else
                            if (fields[idx].fieldType === 'BigDecimal') { %>sameNumber(<% } %><%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %><%
                        if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { %><%
                            if (databaseType === 'cassandra') { %>.array()<% } %>)<% } else
                                if (fields[idx].fieldType === 'Integer') { %><% } else
                                    if (fields[idx].fieldType === 'Long') { %>.intValue()<% } else
                                        if (fields[idx].fieldType === 'Float' || fields[idx].fieldType === 'Double') { %>.doubleValue()<% } else
                                            if (fields[idx].fieldType === 'BigDecimal') { %>)<% } else
                                                if (fields[idx].fieldType === 'Boolean') { %>.booleanValue()<% } else
                                                    if (fields[idx].fieldType === 'ZonedDateTime') { %>)<% } else
                                                        if (fields[idx].fieldType !== 'String') { %>.toString()<% } %>))<%= !reactive ? ')' : '' %><%_ } _%>;
    }
    <% if (fieldsContainOwnerManyToMany === true) { %>
    @SuppressWarnings({"unchecked"})
    public void getAll<%= entityClassPlural %>WithEagerRelationshipsIsEnabled() <% if (!reactive) { %>throws Exception <% } %>{
        <%_ if (service !== 'no') { _%>
        when(<%= entityInstance %>ServiceMock.findAllWithEagerRelationships(any())).thenReturn(<% if (!reactive) { %>new PageImpl(new ArrayList<>())<% } else { %>Flux.empty()<% }%>);
        <%_ } else { _%>
        when(<%= entityInstance %>RepositoryMock.findAllWithEagerRelationships(any())).thenReturn(<% if (!reactive) { %>new PageImpl(new ArrayList<>())<% } else { %>Flux.empty()<% }%>);
        <%_ } _%>

        <%_ if (!reactive) { _%>
        rest<%= entityClass %>MockMvc.perform(get("/api/<%= entityApiUrl %>?eagerload=true"))
            .andExpect(status().isOk());
        <%_ } else { _%>
        webTestClient.get().uri("/api/<%= entityApiUrl %>?eagerload=true")
            .exchange()
            .expectStatus().isOk();
        <%_ } _%>

        <%_ if (service !== 'no') { _%>
        verify(<%= entityInstance %>ServiceMock, times(1)).findAllWithEagerRelationships(any());
        <%_ } else { _%>
        verify(<%= entityInstance %>RepositoryMock, times(1)).findAllWithEagerRelationships(any());
        <%_ } _%>
    }

    @SuppressWarnings({"unchecked"})
    public void getAll<%= entityClassPlural %>WithEagerRelationshipsIsNotEnabled() <% if (!reactive) { %>throws Exception <% } %>{
        <%_ if (service !== 'no') { _%>
        when(<%= entityInstance %>ServiceMock.findAllWithEagerRelationships(any())).thenReturn(<% if (!reactive) { %>new PageImpl(new ArrayList<>())<% } else { %>Flux.empty()<% }%>);
        <%_ } else { _%>
        when(<%= entityInstance %>RepositoryMock.findAllWithEagerRelationships(any())).thenReturn(<% if (!reactive) { %>new PageImpl(new ArrayList<>())<% } else { %>Flux.empty()<% }%>);
        <%_ } _%>

        <%_ if (!reactive) { _%>
        rest<%= entityClass %>MockMvc.perform(get("/api/<%= entityApiUrl %>?eagerload=true"))
            .andExpect(status().isOk());
        <%_ } else { _%>
        webTestClient.get().uri("/api/<%= entityApiUrl %>?eagerload=true")
            .exchange()
            .expectStatus().isOk();
        <%_ } _%>

        <%_ if (service !== 'no') { _%>
        verify(<%= entityInstance %>ServiceMock, times(1)).findAllWithEagerRelationships(any());
        <%_ } else { _%>
        verify(<%= entityInstance %>RepositoryMock, times(1)).findAllWithEagerRelationships(any());
        <%_ } _%>
    }
    <%_ } _%>

    @Test<%= transactionalAnnotation %>
    void get<%= entityClass %>() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%_ if (databaseType === 'cassandra') { _%>
        <%= asEntity(entityInstance) %>.setId(UUID.randomUUID());
        <%_ } _%>
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        // Get the <%= entityInstance %>
        <%_ if (!reactive) { _%>
        rest<%= entityClass %>MockMvc.perform(get("/api/<%= entityApiUrl %>/{id}", <%= asEntity(entityInstance) %>.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
        <%_ } else { _%>
        webTestClient.get().uri("/api/<%= entityApiUrl %>/{id}", <%= asEntity(entityInstance) %>.getId())
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .expectBody()
        <%_ } _%>
        <%_ if (['sql', 'mongodb', 'couchbase', 'cassandra'].includes(databaseType)) {
        _%>
            <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.id").value(<%= reactive ? 'is(' : '' %><%= idValue %>))<%_ } _%><% for (idx in fields) { %>
            <%_ if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { _%>
            <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.<%= fields[idx].fieldName %>ContentType").value(<%= reactive ? 'is(' : '' %><%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE))
            <%_ } _%>
            <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.<%= fields[idx].fieldName %>").value(<%= reactive ? 'is(' : '' %><%
                    if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { %>Base64Utils.encodeToString(<% } else
                        if (fields[idx].fieldType === 'ZonedDateTime') { %>sameInstant(<% } else
                            if (fields[idx].fieldType === 'BigDecimal') { %>sameNumber(<% } %><%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %><%
                        if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { %><%
                            if (databaseType === 'cassandra') { %>.array()<% } %>)<% } else
                                if (fields[idx].fieldType === 'Integer') { %><% } else
                                    if (fields[idx].fieldType === 'Long') { %>.intValue()<% } else
                                        if (fields[idx].fieldType === 'Float' || fields[idx].fieldType === 'Double') { %>.doubleValue()<% } else
                                            if (fields[idx].fieldType === 'BigDecimal') { %>)<% } else
                                                if (fields[idx].fieldType === 'Boolean') { %>.booleanValue()<% } else
                                                    if (fields[idx].fieldType === 'ZonedDateTime') { %>)<% } else
                                                        if (fields[idx].fieldType !== 'String') { %>.toString()<% } %>))<%_ } _%>;
    }
<%_ if (jpaMetamodelFiltering) {  %>

    @Test<%= transactionalAnnotation %>
    void get<%= entityClassPlural %>ByIdFiltering() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        Long id = <%= asEntity(entityInstance) %>.getId();

        default<%= entityClass %>ShouldBeFound("id.equals=" + id);
        default<%= entityClass %>ShouldNotBeFound("id.notEquals=" + id);

        default<%= entityClass %>ShouldBeFound("id.greaterThanOrEqual=" + id);
        default<%= entityClass %>ShouldNotBeFound("id.greaterThan=" + id);

        default<%= entityClass %>ShouldBeFound("id.lessThanOrEqual=" + id);
        default<%= entityClass %>ShouldNotBeFound("id.lessThan=" + id);
    }

<%_
        fields.forEach((searchBy) => {
            // we can't filter by all the fields.
            if (isFilterableType(searchBy.fieldType)) {
                 _%>

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsEqualToSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> equals to <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.equals=" + <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> equals to <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.equals=" + <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>);
    }

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsNotEqualToSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> not equals to <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.notEquals=" + <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> not equals to <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.notEquals=" + <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>);
    }

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsInShouldWork() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> in <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %> or <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.in=" + <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %> + "," + <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> equals to <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.in=" + <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>);
    }

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsNullOrNotNull() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is not null
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.specified=true");

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is null
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.specified=false");
    }
<%_
            }
            if (searchBy.fieldType === 'String') {
                _%>
                @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>ContainsSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> contains <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.contains=" + <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> contains <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.contains=" + <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>);
    }

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>NotContainsSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> does not contain <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.doesNotContain=" + <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> does not contain <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.doesNotContain=" + <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>);
    }

<%_
            }
            // the range criteria
            if (['BigDecimal', 'Byte', 'Double', 'Duration', 'Float', 'Short',
                 'Integer', 'Long', 'LocalDate', 'ZonedDateTime'].includes(searchBy.fieldType)) {
              var defaultValue = 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase();
              var biggerValue = 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase();
              var smallerValue = 'SMALLER_' + searchBy.fieldNameUnderscored.toUpperCase();
              if (searchBy.fieldValidate === true && searchBy.fieldValidateRules.includes('max')) {
                  // if maximum is specified the updated variable is smaller than the default one!
                  if (searchBy.fieldType === 'BigDecimal') {
                      biggerValue = '(' + defaultValue + '.add(BigDecimal.ONE))';
                  } else if (['Duration', 'LocalDate', 'ZonedDateTime'].includes(searchBy.fieldType)) {
                      biggerValue = '(' + defaultValue + '.plus(1, ChronoUnit.DAYS))';
                  } else {
                      biggerValue = '(' + defaultValue + ' + 1)';
                  }
              }
            _%>

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsGreaterThanOrEqualToSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is greater than or equal to <%= defaultValue %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.greaterThanOrEqual=" + <%= defaultValue %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is greater than or equal to <%= biggerValue %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.greaterThanOrEqual=" + <%= biggerValue %>);
    }

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsLessThanOrEqualToSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is less than or equal to <%= defaultValue %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.lessThanOrEqual=" + <%= defaultValue %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is less than or equal to <%= smallerValue %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.lessThanOrEqual=" + <%= smallerValue %>);
    }

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsLessThanSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is less than <%= defaultValue %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.lessThan=" + <%= defaultValue %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is less than <%= biggerValue %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.lessThan=" + <%= biggerValue %>);
    }

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsGreaterThanSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is greater than <%= defaultValue %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.greaterThan=" + <%= defaultValue %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is greater than <%= smallerValue %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.greaterThan=" + <%= smallerValue %>);
    }

<%_         } _%>
<%_     }); _%>
<%_ relationships.forEach((relationship) => { _%>

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= relationship.relationshipNameCapitalized %>IsEqualToSomething() <% if (!reactive) { %>throws Exception <% } %>{
        <%_ if ((relationship.relationshipValidate === true && relationship.relationshipType === 'one-to-one') || relationship.useJPADerivedIdentifier === true) { _%>
        // Get already existing entity
        <%= asEntity(relationship.otherEntityNameCapitalized) %> <%= relationship.relationshipFieldName %> = <%= asEntity(entityInstance) %>.get<%= relationship.relationshipNameCapitalized %>();
        <%_ } else { _%>
        // Initialize the database
        <%= entityInstance %>Repository.saveAndFlush(<%= asEntity(entityInstance) %>);
        <%= asEntity(relationship.otherEntityNameCapitalized) %> <%= relationship.relationshipFieldName %> = <%= relationship.otherEntityNameCapitalized %>ResourceIT.createEntity(em);
        em.persist(<%= relationship.relationshipFieldName %>);
        em.flush();
            <%_ if (relationship.relationshipType === 'many-to-many' || relationship.relationshipType === 'one-to-many') { _%>
        <%= asEntity(entityInstance) %>.add<%= relationship.relationshipNameCapitalized %>(<%= relationship.relationshipFieldName %>);
            <%_ } else { _%>
        <%= asEntity(entityInstance) %>.set<%= relationship.relationshipNameCapitalized %>(<%= relationship.relationshipFieldName %>);
            <%_     if (relationship.ownerSide === false) { _%>
        <%= relationship.relationshipFieldName %>.set<%= relationship.otherEntityRelationshipNameCapitalized %>(<%= asEntity(entityInstance) %>);
            <%_     } _%>
            <%_ } _%>
        <%_ } _%>
        <%= entityInstance %>Repository.saveAndFlush(<%= asEntity(entityInstance) %>);
        <% if (authenticationType === 'oauth2' && relationship.otherEntityName === 'user') { _%>String<%_ } else { _%>Long<% } %> <%= relationship.relationshipFieldName %>Id = <%= relationship.relationshipFieldName %>.getId();

        // Get all the <%= entityInstance %>List where <%= relationship.relationshipFieldName %> equals to <%= relationship.relationshipFieldName %>Id
        default<%= entityClass %>ShouldBeFound("<%= relationship.relationshipFieldName %>Id.equals=" + <%= relationship.relationshipFieldName %>Id);

        // Get all the <%= entityInstance %>List where <%= relationship.relationshipFieldName %> equals to <%= relationship.relationshipFieldName %>Id + 1
        default<%= entityClass %>ShouldNotBeFound("<%= relationship.relationshipFieldName %>Id.equals=" + (<%= relationship.relationshipFieldName %>Id + 1));
    }

<%_ }); _%>
    /**
     * Executes the search, and checks that the default entity is returned.
     */
<%_ if (reactive) { _%>
    private void default<%= entityClass %>ShouldBeFound(String filter) {
        webTestClient.get().uri("/api/<%= entityApiUrl %>?sort=id,desc&" + filter)
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .expectBody()
            .jsonPath("$.[*].id").value(hasItem(<%= idValue %>))<% for (idx in fields) { %>
            <%_ if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { _%>
            .jsonPath("$.[*].<%= fields[idx].fieldName %>ContentType").value(hasItem(<%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE))
            <%_ } _%>
            .jsonPath("$.[*].<%= fields[idx].fieldName %>").value(hasItem(<% if
                    ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { %>Base64Utils.encodeToString(<% } else
                        if (fields[idx].fieldType === 'ZonedDateTime') { %>sameInstant(<% } else
                            if (fields[idx].fieldType === 'BigDecimal') { %>sameNumber(<% } %><%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %><%
                        if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { %><% if (databaseType === 'cassandra') { %>.array()<% } %>)<% } else
                            if (fields[idx].fieldType === 'Integer') { %><% } else
                                if (fields[idx].fieldType === 'Long') { %>.intValue()<% } else
                                    if (fields[idx].fieldType === 'Float' || fields[idx].fieldType === 'Double') { %>.doubleValue()<% } else
                                        if (fields[idx].fieldType === 'BigDecimal') { %>)<% } else
                                            if (fields[idx].fieldType === 'Boolean') { %>.booleanValue()<% } else
                                                if (fields[idx].fieldType === 'ZonedDateTime') { %>)<% } else
                                                    if (fields[idx].fieldType !== 'String') { %>.toString()<% } %>))<%_ } _%>;

        // Check, that the count call also returns 1
        webTestClient.get().uri("/api/<%= entityApiUrl %>/count?sort=id,desc&" + filter)
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectStatus().isOk()
                .expectHeader().contentType(MediaType.APPLICATION_JSON)
                .expectBody().json("1");
    }
<%_ } else { _%>
    private void default<%= entityClass %>ShouldBeFound(String filter) throws Exception {
        rest<%= entityClass %>MockMvc.perform(get("/api/<%= entityApiUrl %>?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(<%= asEntity(entityInstance) %><% if (databaseType === 'sql' && hasOauthUser === true) { %>.getId()<% } else { %>.getId().intValue()<% } %>)))<% fields.forEach((field) => { %>
            <%_ if ((field.fieldType === 'byte[]' || field.fieldType === 'ByteBuffer') && field.fieldTypeBlobContent !== 'text') { _%>
            .andExpect(jsonPath("$.[*].<%= field.fieldName %>ContentType").value(hasItem(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE)))
            <%_ } _%>
            .andExpect(jsonPath("$.[*].<%= field.fieldName %>").value(hasItem(<%
                    if ((field.fieldType === 'byte[]' || field.fieldType === 'ByteBuffer') && field.fieldTypeBlobContent !== 'text') { %>Base64Utils.encodeToString(<% } else
                        if (field.fieldType === 'ZonedDateTime') { %>sameInstant(<% } else
                            if (field.fieldType === 'BigDecimal') { %>sameNumber(<% } %><%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %><%
                        if ((field.fieldType === 'byte[]' || field.fieldType === 'ByteBuffer') && field.fieldTypeBlobContent !== 'text') { %><%
                            if (databaseType === 'cassandra') { %>.array()<% } %>)<% } else
                                if (field.fieldType === 'Integer') { %><% } else
                                    if (field.fieldType === 'Long') { %>.intValue()<% } else
                                        if (field.fieldType === 'Float' || field.fieldType === 'Double') { %>.doubleValue()<% } else
                                            if (field.fieldType === 'BigDecimal') { %>)<% } else
                                                if (field.fieldType === 'Boolean') { %>.booleanValue()<% } else
                                                    if (field.fieldType === 'ZonedDateTime') { %>)<% } else
                                                        if (field.fieldType !== 'String') { %>.toString()<% } %>)))<% }); %>;

        // Check, that the count call also returns 1
        rest<%= entityClass %>MockMvc.perform(get("/api/<%= entityApiUrl %>/count?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(content().string("1"));
    }
<%_ } _%>

    /**
     * Executes the search, and checks that the default entity is not returned.
     */
<%_ if (reactive) { _%>
    private void default<%= entityClass %>ShouldNotBeFound(String filter) {
        webTestClient.get().uri("/api/<%= entityApiUrl %>?sort=id,desc&" + filter)
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .expectBody()
            .jsonPath("$").isArray()
            .jsonPath("$").isEmpty();

        // Check, that the count call also returns 0
        webTestClient.get().uri("/api/<%= entityApiUrl %>/count?sort=id,desc&" + filter)
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .expectBody().json("0");
    }
<%_ } else { _%>
    private void default<%= entityClass %>ShouldNotBeFound(String filter) throws Exception {
        rest<%= entityClass %>MockMvc.perform(get("/api/<%= entityApiUrl %>?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$").isArray())
            .andExpect(jsonPath("$").isEmpty());

        // Check, that the count call also returns 0
        rest<%= entityClass %>MockMvc.perform(get("/api/<%= entityApiUrl %>/count?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(content().string("0"));
    }
<%_ } _%>

<%_  } _%>
    @Test<%= transactionalAnnotation %>
    void getNonExisting<%= entityClass %>() <% if (!reactive) { %>throws Exception <% } %>{
        // Get the <%= entityInstance %>
        <%_ if (!reactive) { _%>
        rest<%= entityClass %>MockMvc.perform(get("/api/<%= entityApiUrl %>/{id}", <% if (['sql', 'mongodb', 'neo4j', 'couchbase'].includes(databaseType)) { %>Long.MAX_VALUE<% } else if (databaseType === 'cassandra') { %>UUID.randomUUID().toString()<% } %>))
            .andExpect(status().isNotFound());
        <%_ } else { _%>
        webTestClient.get().uri("/api/<%= entityApiUrl %>/{id}", <% if (['sql', 'mongodb', 'neo4j', 'couchbase'].includes(databaseType)) { %>Long.MAX_VALUE<% } else if (databaseType === 'cassandra') { %>UUID.randomUUID().toString()<% } %>)
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isNotFound();
        <%_ } _%>
    }
<%_ if (!readOnly) { _%>

    @Test<%= transactionalAnnotation %>
    void update<%= entityClass %>() throws Exception {
    <%_ if (reactive && searchEngine === 'elasticsearch') { _%>
        // Configure the mock search repository
        when(mock<%= entityClass %>SearchRepository.save(any()))
            .thenAnswer(invocation -> Mono.just(invocation.getArgument(0)));
    <%_ } _%>
        // Initialize the database
        <%_ if (databaseType === 'cassandra') { _%>
        <%= asEntity(entityInstance) %>.setId(UUID.randomUUID());
        <%_ } _%>
<%_ if (service !== 'no' && dto !== 'mapstruct') { _%>
        <%= entityInstance %>Service.save(<%= asEntity(entityInstance) %>)<%= callBlock %>;
<%_ } else { _%>
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;
<%_ } _%>

        int databaseSizeBeforeUpdate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();

        // Update the <%= entityInstance %>
        <%= asEntity(entityClass) %> updated<%= asEntity(entityClass) %> = <%= entityInstance %>Repository.findById(<%= asEntity(entityInstance) %>.getId())<%= reactive ? '.block()' : '.get()' %>;
        <%_ if (databaseType === 'sql' && !reactive) { _%>
        // Disconnect from session so that the updates on updated<%= asEntity(entityClass) %> are not directly saved in db
        em.detach(updated<%= asEntity(entityClass) %>);
        <%_ } _%>
        <%_ if (fluentMethods && fields.length > 0) { _%>
        updated<%= asEntity(entityClass) %><% for (idx in fields) { %>
            .<%= fields[idx].fieldName %>(<%= 'UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase() %>)<% if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { %>
            .<%= fields[idx].fieldName %>ContentType(<%= 'UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE)<% } %><% } %>;
        <%_ } else { _%>
            <%_ for (idx in fields) { _%>
        updated<%= asEntity(entityClass) %>.set<%= fields[idx].fieldInJavaBeanMethod %>(<%= 'UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase() %>);
                <%_ if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { _%>
        updated<%= asEntity(entityClass) %>.set<%= fields[idx].fieldInJavaBeanMethod %>ContentType(<%= 'UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE);
                <%_ } _%>
            <%_ } _%>
        <%_ } _%>
        <%_ if (dto === 'mapstruct') { _%>
        <%= asDto(entityClass) %> <%= asDto(entityInstance) %> = <%= entityInstance %>Mapper.toDto(updated<%= asEntity(entityClass) %>);
        <%_ } _%>

        <%_ if (!reactive) { _%>
        rest<%= entityClass %>MockMvc.perform(put("/api/<%= entityApiUrl %>")<% if (testsNeedCsrf) { %>.with(csrf())<% }%>
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(<%= (dto === 'mapstruct' ? asDto(entityInstance) : 'updated' + asEntity(entityClass)) %>)))
            .andExpect(status().isOk());
        <%_ } else { _%>
        webTestClient.put().uri("/api/<%= entityApiUrl %>")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= (dto === 'mapstruct' ? asDto(entityInstance) : 'updated' + asEntity(entityClass)) %>))
            .exchange()
            .expectStatus().isOk();
        <%_ } _%>

        // Validate the <%= entityClass %> in the database
        <%_ if (databaseType === 'couchbase') { _%>
        SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
        <%_ } _%>
        List<<%= asEntity(entityClass) %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
        assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeUpdate);
        <%= asEntity(entityClass) %> test<%= entityClass %> = <%= entityInstance %>List.get(<%= entityInstance %>List.size() - 1);
        <%_ for (idx in fields) { if (fields[idx].fieldType === 'ZonedDateTime') { _%>
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase() %>);
        <%_ } else if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { _%>
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase() %>);
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>ContentType()).isEqualTo(<%= 'UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE);
        <%_ } else { _%>
        assertThat(test<%= entityClass %>.get<%= fields[idx].fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase() %>);
        <%_ } } _%>
        <%_ if (searchEngine === 'elasticsearch') { _%>

        // Validate the <%= entityClass %> in Elasticsearch
        verify(mock<%= entityClass %>SearchRepository, times(<%= service !== 'no' && dto !== 'mapstruct' ? '2' : '1' %>)).save(test<%= entityClass %>);
        <%_ } _%>
    }

    @Test<%= transactionalAnnotation %>
    void updateNonExisting<%= entityClass %>() throws Exception {
        int databaseSizeBeforeUpdate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();

        <%_ if (dto === 'mapstruct') { _%>
        // Create the <%= entityClass %>
        <%= asDto(entityClass) %> <%= asDto(entityInstance) %> = <%= entityInstance %>Mapper.toDto(<%= asEntity(entityInstance) %>);

        <%_ } _%>
        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        <%_ if (!reactive) { _%>
        rest<%= entityClass %>MockMvc.perform(put("/api/<%= entityApiUrl %>")<% if (testsNeedCsrf) { %>.with(csrf())<% }%>
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(<%= (dto === 'mapstruct' ? asDto(entityInstance) : asEntity(entityInstance)) %>)))
            .andExpect(status().isBadRequest());
        <%_ } else { _%>
        webTestClient.put().uri("/api/<%= entityApiUrl %>")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= (dto === 'mapstruct' ? asDto(entityInstance) : asEntity(entityInstance)) %>))
            .exchange()
            .expectStatus().isBadRequest();
        <%_ } _%>

        // Validate the <%= entityClass %> in the database
        <%_ if (databaseType === 'couchbase') { _%>
        SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
        <%_ } _%>
        List<<%= asEntity(entityClass) %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
        assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeUpdate);
        <%_ if (searchEngine === 'elasticsearch') { _%>

        // Validate the <%= entityClass %> in Elasticsearch
        verify(mock<%= entityClass %>SearchRepository, times(0)).save(<%= asEntity(entityInstance) %>);
        <%_ } _%>
    }

    <%
        const prepareFieldForPatchTest = (field, includeCb) => {
            const includeField = includeCb();
            const fieldNameUnderscoreUppercased = field.fieldNameUnderscored.toUpperCase();
            const updateWithValue = includeField ? `UPDATED_${fieldNameUnderscoreUppercased}` : 'null';
            const testWithConstant = includeField ? `UPDATED_${fieldNameUnderscoreUppercased}` : `DEFAULT_${fieldNameUnderscoreUppercased}`;
            return { includeField, updateWithValue, testWithConstant, ...field};
        };
    %>
    @Test<%= transactionalAnnotation %>
    void partialUpdate<%= entityClass %>WithPatch() throws Exception {
<% const fieldsToIncludeInPartialPatchTest = fields.map(field => prepareFieldForPatchTest(field, () => faker.random.boolean())); %>
<%- include('/partials/it_patch_update.partial.java.ejs', {fields: fieldsToIncludeInPartialPatchTest, saveMethod, asEntity, callBlock, callListBlock}); -%>
    }

    @Test<%= transactionalAnnotation %>
    void fullUpdate<%= entityClass %>WithPatch() throws Exception {
<% const fieldsToIncludeInFullPatchTest = fields.map(field => prepareFieldForPatchTest(field, () => true)); %>
<%- include('/partials/it_patch_update.partial.java.ejs', {fields: fieldsToIncludeInFullPatchTest, saveMethod, asEntity, callBlock, callListBlock}); -%>
    }

    @Test<%= transactionalAnnotation %>
    void partialUpdate<%= entityClass %>ShouldThrown() throws Exception {
        // Update the <%= entityInstance %> without id should throw
        <%= asEntity(entityClass) %> partialUpdated<%= asEntity(entityClass) %> = new <%= asEntity(entityClass) %>();

        rest<%= entityClass %>MockMvc.perform(patch("/api/<%= entityApiUrl %>")<% if (testsNeedCsrf) { %>.with(csrf())<% }%>
        .contentType("application/merge-patch+json")
        .content(TestUtil.convertObjectToJsonBytes(<%= 'partialUpdated' + asEntity(entityClass) %>)))
        .andExpect(status().isBadRequest());
    }

    @Test<%= transactionalAnnotation %>
    void delete<%= entityClass %>() <% if (!reactive) { %>throws Exception <% } %>{
<%_ if (reactive && searchEngine === 'elasticsearch') { _%>
        // Configure the mock search repository
    <%_ if (service !== 'no') { _%>
        when(mock<%= entityClass %>SearchRepository.save(any()))
            .thenAnswer(invocation -> Mono.just(invocation.getArgument(0)));
    <%_ } _%>
        when(mock<%= entityClass %>SearchRepository.deleteById(any<%= primaryKeyType %>())).thenReturn(Mono.empty());
<%_ } _%>
        // Initialize the database
        <%_ if (databaseType === 'cassandra') { _%>
        <%= asEntity(entityInstance) %>.setId(UUID.randomUUID());
        <%_ } _%>
<%_ if (service !== 'no' && dto !== 'mapstruct') { _%>
        <%= entityInstance %>Service.save(<%= asEntity(entityInstance) %>)<%= callBlock %>;
<%_ } else { _%>
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;
<%_ } _%>

        int databaseSizeBeforeDelete = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();

        // Delete the <%= entityInstance %>
        <%_ if (!reactive) { _%>
        rest<%= entityClass %>MockMvc.perform(delete("/api/<%= entityApiUrl %>/{id}", <%= asEntity(entityInstance) %>.getId())<% if (testsNeedCsrf) { %>.with(csrf())<% }%>
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());
        <%_ } else { _%>
        webTestClient.delete().uri("/api/<%= entityApiUrl %>/{id}", <%= asEntity(entityInstance) %>.getId())
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isNoContent();
        <%_ } _%>

        // Validate the database contains one less item
        <%_ if (databaseType === 'couchbase') { _%>
        SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
        <%_ } _%>
        List<<%= asEntity(entityClass) %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
        assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeDelete - 1);
        <%_ if (searchEngine === 'elasticsearch') { _%>

        // Validate the <%= entityClass %> in Elasticsearch
        verify(mock<%= entityClass %>SearchRepository, times(1)).deleteById(<%= asEntity(entityInstance) %>.getId());
        <%_ } _%>
    }
<%_ } _%>
    <%_ if (searchEngine !== false) { _%>

    @Test<%= transactionalAnnotation %>
    void search<%= entityClass %>() <% if (!reactive) { %>throws Exception <% } %>{
<%_ if (searchEngine === 'elasticsearch') { _%>
        // Configure the mock search repository
    <%_ if (reactive) { _%>
        when(mock<%= entityClass %>SearchRepository.save(any()))
            .thenAnswer(invocation -> Mono.just(invocation.getArgument(0)));
        <%_ if (pagination !== 'no') { _%>
        when(mock<%= entityClass %>SearchRepository.count()).thenReturn(Mono.just(1L));
        <%_ } _%>
    <%_ } _%>
<%_ } _%>
        // Initialize the database
        <%_ if (databaseType === 'cassandra') { _%>
        <%= asEntity(entityInstance) %>.setId(UUID.randomUUID());
        <%_ } _%>
<%_ if (service !== 'no' && dto !== 'mapstruct') { _%>
        <%= entityInstance %>Service.save(<%= asEntity(entityInstance) %>)<%= callBlock %>;
<%_ } else { _%>
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= asEntity(entityInstance) %>)<%= callBlock %>;
<%_ } _%>
<%_ if (searchEngine === 'elasticsearch') { _%>
    <%_ if (reactive) { _%>
        when(mock<%= entityClass %>SearchRepository.search("id:" + <%= asEntity(entityInstance) %>.getId()<%_ if (pagination !== 'no') { _%>, PageRequest.of(0, 20)<% }%>))
            .thenReturn(Flux.just(<%= asEntity(entityInstance) %>));
    <%_ } else { _%>
        <%_ if (pagination !== 'no') { _%>
        when(mock<%= entityClass %>SearchRepository.search(queryStringQuery("id:" + <%= asEntity(entityInstance) %>.getId()), PageRequest.of(0, 20)))
            .thenReturn(new PageImpl<>(Collections.singletonList(<%= asEntity(entityInstance) %>), PageRequest.of(0, 1), 1));
        <%_     } else { _%>
        when(mock<%= entityClass %>SearchRepository.search(queryStringQuery("id:" + <%= asEntity(entityInstance) %>.getId())))
            .thenReturn(Collections.singletonList(<%= asEntity(entityInstance) %>));
        <%_ } _%>
    <%_ } _%>
<%_ } else if (searchEngine === 'couchbase') { _%>

        // Wait for the <%= entityInstance %> to be indexed
        TestUtil.retryUntilNotEmpty(() -> <%= entityInstance %>Repository.search(<%= entityClass %>.PREFIX, "id:" + <%= entityInstance %>.getId())<% if (reactive) { %>.collectList().block()<% } %>);
<%_ } _%>

        // Search the <%= entityInstance %>
        <%_ if (!reactive) { _%>
        rest<%= entityClass %>MockMvc.perform(get("/api/_search/<%= entityApiUrl %>?query=id:" + <%= asEntity(entityInstance) %>.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
        <%_ } else { _%>
        webTestClient.get().uri("/api/_search/<%= entityApiUrl %>?query=id:" + <%= asEntity(entityInstance) %>.getId())
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .expectBody()
        <%_ } _%>
        <%_ if (['sql', 'mongodb', 'couchbase', 'cassandra'].includes(databaseType)) {
        _%>
            <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].id").value(hasItem(<%= idValue %>))<%= !reactive ? ')' : '' %><%_ } _%><% for (idx in fields) { %>
            <%_ if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { _%>
            <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= fields[idx].fieldName %>ContentType").value(hasItem(<%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE))<%= !reactive ? ')' : '' %>
            <%_ } _%>
            <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= fields[idx].fieldName %>").value(hasItem(<%
                    if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { %>Base64Utils.encodeToString(<% } else
                        if (fields[idx].fieldType === 'ZonedDateTime') { %>sameInstant(<% } else
                            if (fields[idx].fieldType === 'BigDecimal') { %>sameNumber(<% } %><%= 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase() %><%
                        if ((fields[idx].fieldType === 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent !== 'text') { %><%
                            if (databaseType === 'cassandra') { %>.array()<% } %>)<% } else
                                if (fields[idx].fieldType === 'Integer') { %><% } else
                                    if (fields[idx].fieldType === 'Long') { %>.intValue()<% } else
                                        if (fields[idx].fieldType === 'Float' || fields[idx].fieldType === 'Double') { %>.doubleValue()<% } else
                                            if (fields[idx].fieldType === 'BigDecimal') { %>)<% } else
                                                if (fields[idx].fieldType === 'Boolean') { %>.booleanValue()<% } else
                                                    if (fields[idx].fieldType === 'ZonedDateTime') { %>)<% } else
                                                        if (fields[idx].fieldType !== 'String') { %>.toString()<% } %>))<%= !reactive ? ')' : '' %><%_ } _%>;
    }
    <%_ } _%>
}
